package com.usian.listener;

import com.rabbitmq.client.Channel;
import com.usian.JsonUtils;
import com.usian.mapper.DeDuplicationMapper;
import com.usian.pojo.DeDuplication;
import com.usian.pojo.DeDuplicationExample;
import com.usian.pojo.LocalMessage;
import com.usian.service.ItemService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class ItemMQListener {

    @Autowired
    private ItemService itemService;

    @Autowired
    private DeDuplicationMapper deDuplicationMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="item_queue",durable = "true"),
            exchange = @Exchange(value="order_exchage",type= ExchangeTypes.TOPIC),
            key= {"*.*"}
    ))
    public void listen(String msg, Channel channel, Message message) throws Exception {
        LocalMessage localMessage = JsonUtils.jsonToPojo(msg, LocalMessage.class);

        //TODO



        //1:幂等校验
        DeDuplication deDuplication = deDuplicationMapper.selectByPrimaryKey(localMessage.getTxNo());
        if(deDuplication==null){
            //执行业务扣库存
            Integer result = itemService.updateTbItemByOrderId(localMessage.getOrderNo());
            if(!(result>0)){
               throw new RuntimeException("扣减失败");
            }

            //保存重复执行记录表
            DeDuplication deDuplication1 = new DeDuplication();
            deDuplication1.setTxNo(localMessage.getTxNo());
            deDuplication1.setCreateTime(new Date());//？state
            deDuplicationMapper.insertSelective(deDuplication1);
        }

        //执行手动ack消息确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
